package com.zhss.designpattern.iterator;

/**
 * 用迭代器模式的实现练习
 *
 * @author zhonghuashishan
 */
public class IteratorPatternPractice {

	public static void main(String[] args) {
		//初始化类和集合类
		Studet s1 = new Studet("张三");
		Studet s2 = new Studet("李赛");

		ClassRoom classRoom = new ClassRoom(2);
		classRoom.addStudent(s1);
		classRoom.addStudent(s2);

		//使用迭代器迭代集合类
        Iterator iterator = classRoom.getIterator();
        while (iterator.hasNext()){
			System.out.println(iterator.next());
		}


	}


    /**
     * 定义一个迭代器接口
     */
    public interface Iterator {
        boolean hasNext();

        Object next();
    }


    /**
     * 抽象的集合类
     */
    public interface ClassroomCollections {
        /**
         * 获取这个类的迭代器
         */
        Iterator getIterator();
    }

    /**
     * 教室类的迭代器
     */
    public static class ClassroomPracticeIterator implements Iterator {
        private final ClassRoom classroom;
        private Integer index;

        public ClassroomPracticeIterator(ClassRoom classroom) {
            this.classroom = classroom;
            this.index = 0;
        }

        /**
         * 判断数组是否还有下一个元素
         *
         * @return
         */
        public boolean hasNext() {
            if (index < classroom.studets.length) {
                return true;
            }
            return false;
        }

        /**
         * 获取当前位置元素并且下表加1
         */
        public Object next() {
            Studet[] studets = classroom.studets;
            Studet studet = studets[index];
            index++;
            return studet;
        }
    }


    /**
     * 学生类
     */
    public static class Studet {
        private String name;

        public Studet(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Studet{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    /**
     * 班级类:学生的集合类
     */
    public static class ClassRoom implements ClassroomCollections {
        private Studet[] studets;

        //数组的长度
        private int length;
        /**
         * 获取这个类的迭代器：教室类的迭代器
         */
        public Iterator getIterator() {
            return new ClassroomPracticeIterator(this);
        }

        public ClassRoom(Integer length) {
            this.studets = new Studet[length];
        }

        public Studet getStudent(Integer index) {
            return studets[index];
        }

        private int getLast(){
            return studets.length;
        }

        public void addStudent(Studet studet) {
            studets[length] = studet;
            length++;
        }
    }


}
